<template>
  <div class="perception_look" style="padding: 0px 20px" v-loading="loading" element-loading-background="rgba(255, 255, 255, 0.99)" element-loading-text="拼命加载中">
    <el-row>
      <h3 style="line-height: 1.22;font-weight: 600">{{ info.title }}</h3>
    </el-row>
    <el-row style="margin: 10px 0" type="flex" align="middle" justify="start">
      <div style="padding-top: 2.9px;"><el-avatar :src="info.touxiangsrc?info.touxiangsrc:imgsrc" :size="35" ></el-avatar></div>
      <div style="margin: 0 0 0 5px">
        <div style="font-weight: 600">{{ info.name2?info.name2:info.name }}</div>
        <div style="color: #858585;font-size: 12px">生命生生不息</div>
      </div>
    </el-row>
    <el-row>
      <BigImg :show="bigImg.show" :src="bigImg.src" @closeBig="BigImgClose"></BigImg>
      <article v-html="info.body" class="line-numbers">
      </article>
      <footer>
        <el-divider content-position="right">{{ info.name2?info.name2:info.name }}</el-divider>
        <span>{{ info.cz==0?"发布于":"编辑于" }} {{ info.time }}</span>
        <el-row type="flex" justify="start" align="middle" class="gongneng">
          <div>
            <van-icon name="eye-o" size="20" color="#858585" v-show="islll" />
            <van-icon name="eye" size="20" color="#ff0000" v-show="!islll" />
            <span>{{ info.lll }}人浏览</span>
          </div>
          <div @click="todz" style="cursor: pointer;">
            <van-icon name="good-job-o" size="20" color="#858585" v-show="isdz"/>
            <van-icon name="good-job" size="20" color="#ff0000" v-show="!isdz"/>
            <span>{{ info.dz }}人点赞</span>
          </div>
          <div @click="pl()" style="cursor: pointer;">
            <van-icon name="chat-o" size="20" color="#858585" v-show="!ispl" />
            <van-icon name="chat" size="20" color="#858585" v-show="ispl" />
            <span v-show="!ispl">{{ info.pl }}人评论</span>
            <span v-show="ispl">评论</span>
          </div>
          <div v-if="delflag" @click="more" style="cursor: pointer;">
            <van-icon name="ellipsis" size="20" color="#858585" />
            <span>更多</span>
          </div>
        </el-row>
      </footer>

      <el-collapse-transition>
        <PerceptionComment v-show="ispl" :pid="id.toString()" :count="info.pl" @addcount="updateCount"></PerceptionComment>
      </el-collapse-transition>

      <el-collapse-transition>
        <div v-if="ismore" class="bottom_tool">
          <p @click="edit"><van-icon name="edit" />编辑文章</p>
          <p @click="del" ><van-icon name="cross"/>删除文章</p>
          <p @click="editStute(1)" v-if="info.overt==0"><van-icon name="closed-eye"/>仅自己可看</p>
          <p @click="editStute(0)" v-else><van-icon name="friends-o"/>公开文章</p>
        </div>
      </el-collapse-transition>
<!--      <transition enter-active-class="animate__animated animate__fadeInDown" leave-active-class="animate__animated animate__fadeOutDown">

      </transition>-->
    </el-row>
  </div>
</template>

<script>
import userimg from "@/assets/userAvatar.png";
import utils from "@/utils/time"
import PerceptionComment from "@/components/PerceptionComment";
import qs from "qs";
import {mapState} from 'vuex'
import {delArticle, getArticle, recordArticle, setOvert} from "../../utils/api";
import BigImg from "../../components/BigImg";
import wxChat from "../../utils/wxShare";
import Prism from "prismjs";
import "prismjs/themes/prism-okaidia.css";
export default {
  name: "PerceptionLook",
  data(){
    return {
      id:'',
      info: '',
      imgsrc:userimg,
      loading:true,
      isdz:true,
      islll:true,
      lllsetTimeout:'',
      ispl:false,
      delflag:false,
      ismore:false,
      bigImg:{
        show:false,
        src:null
      },
      timeout:'' //浏览计时器
    }
  },
  created() {
    document.title="黑侠的小圈子"
    this.inint();
    this.id = this.$route.query.id;
    getArticle({id:this.id}).then(respose=>{
      if(respose.status!==200){
        this.$notify({
          title: '无法查看',
          message: respose.body,
          type: 'error'
        });
        return
      }
      this.info=respose.body;
      this.$nextTick(() => {
        Prism.highlightAll()
      })
      document.title=this.info.title+"-黑侠的小圈子"
      this.lllsetTimeout = setTimeout(()=>{
        if(this.islll){
          this.info.lll++;
          this.islll=false
          //发起浏览量请求

          /*判断该用户是否为当日首次发布*/
          let day = 0
          let localStorageValue = localStorage.getItem('dailyBrowsing')
          if(!localStorageValue){
            day = 1
          }else{
            if(new Date().getDate()!=new Date(localStorageValue-0).getDate()){
              day = 1
            }else{
              /*同一天 进一步判断是否为当天*/
              let _time = new Date()
              if(!(localStorageValue-0>=new Date(_time.setDate(_time.getDate())).setHours(0,0,0,0) && localStorageValue-0<new Date(_time.setDate(_time.getDate()+1)).setHours(0,0,0,0))){
                day = 1
              }
            }
          }
          recordArticle(qs.stringify({pid:this.info.id,cz:1,sl:1,day})).then(res=>{
            if(res.wxdaily){
              if(res.wxdaily!=0){
                this.$notify({
                  title: '浏览成功',
                  message: `获得奖励￥${res.wxdaily}元`,
                  type: 'success'
                });
              }
              localStorage.setItem('dailyBrowsing',new Date().getTime()+'')
            }
          }).catch(err=>{
            console.log(err)
          })
        }
      },10000)
      if(this.info.touxiangsrc){
        this.info.touxiangsrc=this.info.touxiangsrc.replace(/public/, 'http://cloud.pinggai8.com');
      }
      this.info.time=utils.timestampToTime(this.info.time,5);
      this.loading=false;

      this.$nextTick(()=>{
        let imgs = document.querySelectorAll('article img')
        imgs.forEach(v=> {
          v.onclick = ()=>{
            this.bigImg.show = true
            this.bigImg.src = v.src
          }
        })
        wxChat.wxLogin({
          desc: this.info?.body?.replace(/<[^<>]+>/g, "").replace(/&nbsp;/gi, "").replace(/\s/g, ""),
          imgUrl: imgs[0]?.src
        })
      })

      respose.cz.forEach(item=>{
        if(item===1){
          this.islll=false;
        }else if(item===2){
          this.isdz=false;
        }
      })
      /*需要考虑如果用户直接访问这个页面呢*/
      /*console.log(this.userid)*/
      if(this.info.u_id==this.userid || this.userqx>=9){
        this.delflag=true
      }

    }).catch(error=>{
      console.log(error);
    })
  },
  methods:{
    inint(){
      //bug 情景在现 在id为6的文章关闭浏览器，那么缓存没有清除，下次打开另外一篇文章，就会操作打开文章，因为我们的文章id是取url中的参数，
      //如果加一个新的缓存字段来保存离开前的文章id，但是就怕有人修改缓存，影响了数据库的信息
      //那如果添加或删除之前先判断用户有没有相关操作
      /*存在点赞操作的缓存*/
      let id = localStorage.getItem("wz");
      if(localStorage.getItem("ydz") && localStorage.getItem("ndz")){
        if(localStorage.getItem("ydz")>localStorage.getItem("ndz")){
          //取消点赞
          recordArticle(qs.stringify({pid:id,cz:2,sl:-1}))
        }else if(localStorage.getItem("ydz")<localStorage.getItem("ndz")){
          //增加点赞
          recordArticle(qs.stringify({pid:id,cz:2,sl:1}))
        }
        localStorage.removeItem("ydz");
        localStorage.removeItem("ndz");
        localStorage.removeItem("wz");
      }
    },
    todz(){
      localStorage.setItem("wz",this.info.id);
      localStorage.setItem("ydz",this.info.dz);
      this.isdz=!this.isdz;
      if(this.isdz && this.info.dz!=0){
        this.info.dz--;
      }else{
        this.info.dz++;
      }
      localStorage.setItem("ndz",this.info.dz);
    },
    pl(){

      this.ispl=!this.ispl;

    },
    more(){
      this.ismore=!this.ismore;
    },
    edit(){
      this.$router.replace({name:'perceptionedit',params:{pinfo:this.info}})
    },
    del(){
      this.$dialog.confirm({
        title: '提示',
        message:'删除后将无法恢复，是否删除？',
      }).then(() => {
        /*确定删除文章*/
        delArticle(qs.stringify({pid:this.info.id})).then(respose=>{
          if(respose.status===200){
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success'
            });
            /*防止用户疯狂点击按钮，成功后立即跳转到文章列表*/
            this.$router.replace({path:"/perception",query:{del:this.info.id}});
          }else{
            this.$notify({
              title: '错误',
              message: '删除错误',
              type: 'error'
            });
            /*防止用户疯狂点击按钮，成功后立即跳转到文章列表*/
            this.$router.replace("/perception");
          }
        }).catch(error=>{
          console.log(error)
        })
      }).catch(() => {
        /*不删除*/
      });
    },
    editStute(v){
      setOvert(qs.stringify({id:this.id,overt:v})).then(res=>{
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success'
        });
        /*if(v==1){
          this.$router.replace({query:{...this.$route.query,del:this.id}})
          this.$router.push({path:'',query:{del:this.id}})
        }*/
      }).catch(err=>{
        this.$notify({
          title: '失败',
          message: err,
          type: 'error'
        });
      })
    },
    BigImgClose(){
      this.bigImg.show = false
      this.bigImg.src = null
    },
    updateCount(){
      this.info.pl++
    }
  },
  beforeDestroy() {
    clearTimeout(this.lllsetTimeout);
    clearTimeout(this.timeout)
    this.inint();
  },
  components:{
    BigImg,
    PerceptionComment,
  },
  computed:{
    ...mapState([
      "userid","userqx"
    ])
  }
}
</script>

<style scoped>
@import '~animate.css';
.el-divider--horizontal{
  margin-bottom: 0px;
}
article{
  min-height: 60vh;
  padding: 5px 0;
}
article>>>*{
  line-height: 2;
  word-wrap:break-word
}
article>>>p>img:first-child{
  text-indent: 0rem!important;
}
footer>span{
  font-size: 14px;
  color: #858585;
}
.gongneng{
  margin: 24px 0 10px;
}
.gongneng>div{
  margin-right:15px;
  overflow: hidden;
  max-height: 21px;
}
.gongneng>div>i{
  vertical-align: middle;
  margin-right: 3px
}
.gongneng>div>span{
  vertical-align: middle;
  color:#858585
}
.bottom_tool p{
  margin: 0 20px 0 0;
  padding-bottom: 10px;
  float: left;
}
>>>img,>>>video{
  max-width: 100%!important;
  margin: 0 auto;
}

>>>article p,
>>>article li {
  white-space: pre-wrap; /* 保留空格 */
}

>>>article blockquote {
  border-left: 8px solid #d0e5f2;
  padding: 10px 10px;
  margin: 10px 0;
  background-color: #f1f1f1;
}

>>>article table {
  border-collapse: collapse;
}
>>>article td,
>>>article th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}
>>>article th {
  background-color: #f1f1f1;
}

>>>article ul,
>>>article ol {
  padding-left: 20px;
}
>>>article ul{
  list-style-type: disc;
}
>>>article ol {
  list-style-type: decimal;
}

>>>article input[type="checkbox"] {
  margin-right: 5px;
}
</style>
